<template>
  <c-form
    ref="formRef"
    label-width="100px"
    isDialog
    :model="formData"
    :rows="formRows"
    @submit="onSubmit"
  ></c-form>
</template>

<script setup name="group-create" lang="jsx">
import { ref, computed } from 'vue';

// components
import { ElMessage } from 'element-plus';

// modal,pinia
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

import { useFetch } from '@/hooks/useFetch/index.js';

// api
import { allTypeGroup, userListGroup } from '@/apis/user';
import { createGroup, editeGroup } from '@/apis/images';

const emit = defineEmits(['refresh']);

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

// 分类列表
const { loading: typeLoading, data: typeGroupData } = useFetch({
  api: props.userType == 1 ? allTypeGroup : userListGroup,
});

const formData = ref({
  _id: '',
  name: '',
  group_type: '',
  group_sort: 0,
  status: 0,
  group_cover: {},
});

const formRows = ref([
  {
    formType: 'upload-img',
    prop: 'group_cover',
    label: '分组封面:',
    size: 2,
    isIf: computed(() => props.userType == 1),
  },
  { formType: 'input', prop: 'name', label: '分组名称:' },
  {
    formType: 'select',
    prop: 'group_type',
    label: '图像类型:',
    optionList: computed(() => typeGroupData.value),
    optionProps: { label: 'label', value: 'value' },
    loading: computed(() => typeLoading.value),
  },
  { formType: 'input-number', prop: 'group_sort', label: '分组权重:' },
  {
    formType: 'switch',
    prop: 'status',
    label: '显示状态:',
    inactiveValue: 1,
    activeValue: 0,
  },
]);

// 获取传递弹窗的数据
const modalData = modalStore.getModal();
if (modalData._id) {
  console.log(modalData, 'modalData');
  formData.value._id = modalData._id;
  formData.value.name = modalData.name;
  formData.value.group_type = modalData.group_type;
  formData.value.group_sort = modalData.group_sort;
  formData.value.status = modalData.status;
  formData.value.group_cover = {
    ...modalData.group_cover,
    file: { size: modalData.group_cover.size },
    imageUrl: modalData.group_cover.url,
  };
}

const formRef = ref(null);
const onSubmit = async (values, instance, done) => {
  instance.loading = true;
  console.log(formData.value, 'formData');

  if (formData.value._id) {
    const groupRes = await editeGroup({
      ...formData.value,
    });

    if (groupRes.code == 0) {
      ElMessage.success('添加成功');
      modalStore.closeModal('group-create');
    }
  } else {
    let obj = { ...formData.value };

    if (props.userType) {
      obj['userid'] = -1;
    }

    const groupRes = await createGroup(obj);

    if (groupRes.code == 0) {
      ElMessage.success('添加成功');
      modalStore.closeModal('group-create');
    }
  }

  emit('refresh');

  done();
  instance.loading = false;
};
</script>

<style lang="scss" scoped></style>
